package com.zzz.proxy;

import com.zzz.framework.config.http.LoadBalance;
import com.zzz.framework.exception.BizException;
import com.zzz.framework.model.R;
import com.zzz.framework.util.MyJsonUtil;
import okhttp3.Cookie;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 跨域代理
 */
@RestController
@RequestMapping("ajaxProxy")
public class AjaxProxyAction {

    @Autowired
    private OkHttpClient okHttpClient;

    @Autowired
    private LoadBalance loadBalance;


    private final String tokenKey = "zg_sso_token";
    private final String tokenValue = "M5orrHJCEQcIqJ_vb08iLty1yFWdM4ZJQUDdpcUeTs4TTMs-c8wDeEJm4UhzLI5Jp5xnsQ3QL2jl98fQNX0zBw..";

    @PostMapping("/{systemAlias}/{*path}")
    public R viewSystemPath(@PathVariable String systemAlias, @PathVariable String path, @RequestBody Object req) {
        final String domain = loadBalance.getDomainBySystemAlias(systemAlias);
        // 创建 Cookie 对象
        Cookie cookie = new Cookie.Builder()
                .name(tokenKey)
                .value(tokenValue)
                .domain(domain.replace("http://", "").replace("https://", ""))
                .build();
        Request request = new Request.Builder()
                .url(domain + path)
                .header("Cookie", cookie.toString())
                .post(okhttp3.RequestBody.create(MyJsonUtil.toJsonStr(req).getBytes(), okhttp3.MediaType.parse("application/json")))
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new BizException(response.code() + ": " + response.message());
            }
            String resp = response.body().string();
            return R.data(MyJsonUtil.toBean(resp, Map.class));
        } catch (BizException e) {
            throw e;
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
    }
}
